<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" class="sub-navbar">
        <el-button style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="视频名称">
          <el-input v-model="postForm.title" class="video-textarea" />
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="视频简介">
          <el-input v-model="postForm.description" :rows="1" type="textarea" class="video-textarea" autosize placeholder="视频简介" />
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="部门">
          <el-input v-model="postForm.department" />
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="表演者">
          <el-input v-model="postForm.actor" :rows="1" type="textarea" class="video-textarea" autosize />
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="视频链接">
          <el-input v-model="postForm.url" class="video-textarea" placeholder="https://" />
        </el-form-item>

        <el-form-item style="margin-bottom: 30px;" label-width="70px" label="封面图片">
          <div style="width:200px;height:200px;position:relative;">
            <el-input ref="coverFile" v-model="postForm.cover_file" type="file" class="coverFile" :rows="1" accept="image/jpeg,image/jpg,image/png" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0" @change="changeCover" />
            <img ref="coverUrl" style="width:100%;" :src="coverUrl">
          </div>
        </el-form-item>

        <el-form-item v-show="isEdit" style="margin-bottom: 30px;" label-width="70px" label="视频预览">
          <video ref="playVideo" style="width: 400px;" controls="controls" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchVideo, createVideo, updateVideo } from '@/api/video'
import { jsError } from '@/api/js-error'

const defaultForm = {
  title: '', // 视频标题
  description: '', // 视频描述
  url: '', // 视频链接
  cover_file: undefined, // 视频封面图片文件
  cover_url: '', // 视频封面图片链接
  id: undefined
}

export default {
  name: 'OperateVideo',
  description: '新增或修改均可使用',
  components: { Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: this.mapper[rule.field] + '必须',
          type: 'error'
        })
        callback(new Error(this.mapper[rule.field] + '必须'))
      } else {
        callback()
      }
    }
    return {
      mapper: { title: '视频名称', url: '视频链接' },
      postForm: Object.assign({}, defaultForm),
      rules: {
        title: [{ validator: validateRequire }],
        url: [{ validator: validateRequire }]
      },
      tempRoute: {},
      coverUrl: process.env.VUE_APP_RESOURCE_PREFIX + 'static/image/upload.png'
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 修改时才会执行该方法
    fetchData(id) {
      fetchVideo(id).then(response => {
        this.postForm = response.data

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()

        if (this.postForm.url !== '' && this.postForm.url !== null) {
          this.$refs.playVideo.src = this.postForm.url
        }
        if (this.postForm.cover_url !== '' && this.postForm.cover_url !== null) {
          this.$refs.coverUrl.src = this.postForm.cover_url
        }
      }).catch(err => {
        jsError({
          filename: 'video.OperateVideo.vue',
          title: 'fetchVideo(' + id + ')',
          message: err.message
        })
      })
    },
    // 修改时才会执行该方法
    setTagsViewTitle() {
      const title = '修改视频'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 修改时才会执行该方法
    setPageTitle() {
      const title = '修改视频'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      // this.loading = true

      var formData = new FormData()
      formData.append('title', this.postForm.title)
      formData.append('description', this.postForm.description)
      formData.append('department', this.postForm.department)
      formData.append('actor', this.postForm.actor)

      if (this.$refs.coverFile.$refs.input.files.length > 0) {
        formData.append('cover_file', this.$refs.coverFile.$refs.input.files[0])
      }

      if (this.postForm.id) {
        updateVideo(formData)
          .then(data => {
            this.$notify({
              title: '成功',
              message: '修改视频成功',
              type: 'success',
              duration: 2000
            })
          })
          .catch(err => {
            jsError({
              filename: 'video.OperateVideo.vue',
              title: 'updateVideo(' + this.postForm.id + ')',
              message: err.message
            })
          })
      } else {
        createVideo(formData)
          .then(data => {
            this.$notify({
              title: '成功',
              message: '添加视频成功',
              type: 'success',
              duration: 2000
            })
          })
          .catch(err => {
            jsError({
              filename: 'video.OperateVideo.vue',
              title: 'createVideo()',
              message: err.message
            })
          })
      }
    },
    changeCover() {
      if (this.$refs.coverFile.$refs.input.files.length > 0) {
        this.$refs.coverUrl.src = window.URL.createObjectURL(this.$refs.coverFile.$refs.input.files[0])
      }
    }
  }
}

// .video-textarea /deep/ {
</script>

<style lang="scss">
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .video-textarea {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }

  .coverFile .el-input__inner, .videoFile .el-input__inner {
    width: 100%;
    height: 100%;
  }
</style>
